﻿using Meta.Vlc.Interop.MediaPlayer;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VideoCarousel.Control;
using VideoCarousel.Entity;
using VideoCarousel.Tool;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;

namespace VideoCarousel
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, IPlayCtr
    {
        private System.Windows.Threading.DispatcherTimer DispatcherTimer;
        
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            this.Closing += MainWindow_Closing;
            CarouselInit();

        }
        private bool isClose = false;
        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            isClose = true;
            _vlc.Dispose();

            if (DispatcherTimer != null)
                DispatcherTimer.Stop();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
      
            bool isFullScreen = Convert.ToBoolean(VCLib.Util.ConfigHelp.ReadConfig("isFullScreen"));
            
            if (isFullScreen)
            {
                this.WindowStyle = WindowStyle.None;
                this.ResizeMode = ResizeMode.NoResize;
                this.Left = VCLib.Util.ConfigHelp.ReadConfig<double>("left");
                this.Top = VCLib.Util.ConfigHelp.ReadConfig<double>("top");
                this.Width = VCLib.Util.ConfigHelp.ReadConfig<double>("width");
                this.Height = VCLib.Util.ConfigHelp.ReadConfig<double>("height");
                this.Topmost = true;
            }
            DispatcherTimer = new System.Windows.Threading.DispatcherTimer(
                new TimeSpan(0, 0, 0, 10, 0),
                System.Windows.Threading.DispatcherPriority.Normal,
                Timer_Elapsed,
                this.Dispatcher);
            DispatcherTimer.Start();
            this.MouseMove += MainWindow_MouseMove;
            AppControl.Instance.PlayCtr = this;
            AppControl.Instance.rootPath=rootTemp;
            AppControl.Instance.Init();
            this.DataContext = AppControl.Instance;
            SetVolume(AppControl.Instance.PlayStateInfo.Vol);
            Full(AppControl.Instance.PlayStateInfo.IsFull);
            this._vlc.StateChanged += _vlc_StateChanged;
        }

        private void _vlc_StateChanged(object sender, Control.VlC.MediaState e)
        {
            if(e == Control.VlC.MediaState.Stopped)
            {
                if (isStop)
                {
                    isStop = true;
                    return;
                }
                if (AppControl.Instance.PlayStateInfo.PlayType == 1)
                {
                    System.Threading.Tasks.Task.Run(() => {
                        Dispatcher.Invoke(() => {
                            if (AppControl.Instance.PlayStateInfo != null)
                            {
                                Play();
                            }
                        });
                    });
                }
                else if (AppControl.Instance.PlayStateInfo.PlayType == 2)
                {
                    System.Threading.Tasks.Task.Run(() => {
                        AppControl.Instance.NextPlay();
                    });

                }
                else if (AppControl.Instance.PlayStateInfo.PlayType == 3)
                {
                    System.Threading.Tasks.Task.Run(() => {
                        AppControl.Instance.RandowPlay();
                    });

                }
                else
                {
                    AppControl.Instance.PlayStateInfo.PlayState = 0;
                }
            }
        }

        private string rootTemp = null;
      
        private void NotCarouselSelect_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Filter = "视频|*.mp4;*.mov;*.mp4;*.avi;*.rmvb;*.flv;*.3gp;*.mpeg;*.mpg4;*.wmva;";
            if(openFileDialog.ShowDialog()== true)
            {
                _vlc.Stop();
                _vlc.Load(openFileDialog.FileName);
                _vlc.Play();
            }
        }
        private void CarouselInit()
        {


            MenuItem updateFolder = new MenuItem() { Header = "更换视频文件夹" };
            updateFolder.Click += UpdateFolder_Click;
            contextMenu.Items.Insert(0, updateFolder);



            string folder = VCLib.Util.ConfigHelp.ReadConfig("videoFolder");
        check2:

            if (System.IO.Directory.Exists(folder))
            {
                rootTemp = folder;
            }
            else
            {
                var msgRes = MessageBox.Show("视频文件夹不存在，是否重新选择路径", "提示", MessageBoxButton.YesNo);
                if (msgRes == MessageBoxResult.Yes)
                {
                    folder = OpenFolder();
                    if(folder == null)
                    {
                        this.Close();
                        return;
                    }
                    VCLib.Util.ConfigHelp.SaveConfig("videoFolder", folder);

                    goto check2;
                }
                else
                {
                    this.Close();
                    return;
                }
            }

        }

        private void UpdateFolder_Click(object sender, RoutedEventArgs e)
        {
            string folder = OpenFolder();
            if (folder != null)
            {
                VCLib.Util.ConfigHelp.SaveConfig("videoFolder", folder);
                MessageBox.Show("保存成功，重启生效");
            }

        }

        Point mp;
        private bool? mouseIsShow;
        private void Timer_Elapsed(object sender, EventArgs e)
        {
            var c = Mouse.GetPosition(this);
            if (c.X == mp.X && c.Y == mp.Y)
            {
                mp.X = c.X;
                mp.Y = c.Y;
                if (mouseIsShow == false)
                    return;
                Mouse.OverrideCursor = Cursors.None;
                mouseIsShow = false;
            }
            else
            {
                mp.X = c.X;
                mp.Y = c.Y;
                if (mouseIsShow == true)
                    return;
                Mouse.OverrideCursor = Cursors.Arrow;
                mouseIsShow = true;
            }
        }
        private void MainWindow_MouseMove(object sender, MouseEventArgs e)
        {
            if (Mouse.OverrideCursor == Cursors.None)
            {
                mouseIsShow = true;
                Mouse.OverrideCursor = Cursors.Arrow;
            }
        }
       

        private string OpenFolder()
        {
            Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog openFileDialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            openFileDialog.IsFolderPicker = true;
            openFileDialog.Multiselect = true;
            if (openFileDialog.ShowDialog() == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok)
            {
                return openFileDialog.FileName;
            }
            return null;

        }
        private void _vlc_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (_vlc.MediaState == VideoCarousel.Control.VlC.MediaState.Playing)
            {
                _vlc.Pause();
            }
            else if (_vlc.MediaState == VideoCarousel.Control.VlC.MediaState.Stopped)
            {
                _vlc.Play();

            }
            else if (_vlc.MediaState == VideoCarousel.Control.VlC.MediaState.Paused)
            {
                _vlc.Play();

            }
            else if (_vlc.MediaState == VideoCarousel.Control.VlC.MediaState.NothingSpecial)
            {
                _vlc.Play();

            }
            else if (_vlc.MediaState == VideoCarousel.Control.VlC.MediaState.Opening)
            {
                _vlc.Pause();

            }
        }

        

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

   
        private void Set_Click(object sender, RoutedEventArgs e)
        {
            var topmost = this.Topmost;
            if (topmost)
                this.Topmost = false;
            SetWindow.Set();
            if (topmost)
                this.Topmost = true;

        }

        private string currentFullName = null;
        public void Play()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (AppControl.Instance.PlayStateInfo.FullName != null)
                {
                    if (AppControl.Instance.PlayStateInfo.PlayState == 0)
                        _vlc.Load(AppControl.Instance.PlayStateInfo.FullName);
                    AppControl.Instance.PlayStateInfo.PlayState = 1;
                    _vlc.Play();
                }
            }));
        }
        public void Play(string fileName)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("文件不存在");
                _vlc.Load(fileName);
                _vlc.Play();
                AppControl.Instance.PlayFileNameUpdate(fileName);
            }));
        }
        bool isStop = false;
        public void Stop()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                AppControl.Instance.PlayStateInfo.PlayState = 0;
                isStop = true;
                _vlc.Stop();

            }));
        }

        public void Pause()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {

                _vlc.Pause();
                AppControl.Instance.PlayStateInfo.PlayState = 2;
            }));
        }

        public void SetVolume(int volume)
        {
            _vlc.Dispatcher.Invoke((Action)(() =>
            {
                _vlc.Volume = volume;
            }));
        }
        public void Seek(double seek)
        {
            _vlc.Dispatcher.Invoke((Action)(() =>
            {
                _vlc.CurrentLength = TimeSpan.FromSeconds(seek);
            }));
        }

        public void UpdatePlaySate()
        {
            if (isClose) return;
            this.Dispatcher.Invoke((Action)(() => {
                AppControl.Instance.PlayStateInfo.Current = _vlc.CurrentLength.TotalSeconds;
                AppControl.Instance.PlayStateInfo.Count = _vlc.Length.TotalSeconds;
                AppControl.Instance.PlayStateInfo.Vol = _vlc.Volume;
                AppControl.Instance.PlayStateInfo.IsFull = _vlc._play.Stretch == Stretch.Fill ? 1 : 0;
            }));
        }

        public void Full(int isFull)
        {
            this.Dispatcher.Invoke(() => {
                if (isFull == 1)
                    _vlc._play.Stretch = Stretch.Fill;
                else
                    _vlc._play.Stretch = Stretch.Uniform;
            });
        }

        private void stop_click(object sender, RoutedEventArgs e)
        {
            Stop();
        }
    }
}
